from pathlib import Path
from typing import List, Optional
from jinja2 import Environment, FileSystemLoader
from bookmark_parser.parser import Category, Bookmark
import shutil
import json

class PortalGenerator:
    """门户网站生成器"""
    
    def __init__(self, output_dir: str, template_dir: str = "templates"):
        """初始化生成器
        
        Args:
            output_dir: 输出目录
            template_dir: 模板目录
        """
        self.output_dir = Path(output_dir)
        self.template_dir = Path(template_dir)
        
        # 创建Jinja2环境
        self.env = Environment(
            loader=FileSystemLoader(self.template_dir),
            autoescape=True
        )
        
    def generate(self, root_category: Category, title: str = "收藏夹导航"):
        """生成门户网站
        
        Args:
            root_category: 根分类对象
            title: 网站标题
        """
        # 创建输出目录
        self.output_dir.mkdir(parents=True, exist_ok=True)
        
        # 复制静态文件
        self._copy_static_files()
        
        # 生成数据文件
        self._generate_data_file(root_category)
        
        # 生成首页
        self._generate_index(root_category, title)
        
        # 生成分类页面
        for category in root_category.subcategories.values():
            self._generate_category_page(category, title)
            
    def _copy_static_files(self):
        """复制静态文件到输出目录"""
        static_dir = self.template_dir / "static"
        if static_dir.exists():
            output_static = self.output_dir / "static"
            if output_static.exists():
                shutil.rmtree(output_static)
            shutil.copytree(static_dir, output_static)
            
    def _generate_data_file(self, root_category: Category):
        """生成数据JSON文件
        
        Args:
            root_category: 根分类对象
        """
        def serialize_category(category: Category) -> dict:
            return {
                "name": category.name,
                "bookmarks": [
                    {
                        "title": b.title,
                        "url": b.url,
                        "add_date": b.add_date,
                        "icon": b.icon
                    }
                    for b in category.bookmarks
                ],
                "subcategories": {
                    name: serialize_category(cat)
                    for name, cat in category.subcategories.items()
                }
            }
            
        data = serialize_category(root_category)
        data_file = self.output_dir / "data.json"
        with open(data_file, "w", encoding="utf-8") as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
            
    def _generate_index(self, root_category: Category, title: str):
        """生成首页
        
        Args:
            root_category: 根分类对象
            title: 网站标题
        """
        template = self.env.get_template("index.html")
        output = template.render(
            categories=root_category.subcategories.values(),
            site_title=title
        )
        
        index_file = self.output_dir / "index.html"
        with open(index_file, "w", encoding="utf-8") as f:
            f.write(output)
            
    def _generate_category_page(self, category: Category, title: str):
        """生成分类页面
        
        Args:
            category: 分类对象
            title: 网站标题
        """
        template = self.env.get_template("category.html")
        output = template.render(
            category=category,
            site_title=title
        )
        
        # 创建分类目录
        category_dir = self.output_dir / category.name
        category_dir.mkdir(exist_ok=True)
        
        # 生成分类页面
        page_file = category_dir / "index.html"
        with open(page_file, "w", encoding="utf-8") as f:
            f.write(output)
            
        # 递归生成子分类页面
        for subcategory in category.subcategories.values():
            self._generate_category_page(subcategory, title) 